package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.brwh.kit.HttpKit;
import com.seeyon.apps.brwh.kit.StrKit;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.logging.Log;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.*;


@Path("jssdk")
@Produces({MediaType.APPLICATION_JSON})
public class CustomNewTaskResources extends BaseResource {

    private static final Log log = CtpLogFactory.getLog(CustomNewTaskResources.class);

    private static final String userName = AppContext.getSystemProperty("brwh.restName");
    private static final String templateCode = AppContext.getSystemProperty("brwh.rwdaUnformTemapleCode");
    private static final String accessAddress = AppContext.getSystemProperty("brwh.oaOuterNetIp");
    private static final String password = AppContext.getSystemProperty("brwh.restPassWord");
    private String localAddr = AppContext.getRawRequest().getLocalAddr();
    private String port = String.valueOf(AppContext.getRawRequest().getLocalPort());
    private String tokenUrl = "http://"+localAddr+":"+port+"/seeyon/rest/token";
    private String bpmUrl = "http://"+localAddr+":"+port+"/seeyon/rest/bpm/process/start";
    private CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");

    /**
     * 新建待发任务(待发)
     *
     * @param param 请求参数，格式为Map<String, Object>
     * @return Response 返回响应对象
     * @throws Exception 异常处理
     */
    @POST
    @Path("brwh/newTask")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getOrganizationData(Map<String, Object> param) throws Exception {
        log.info("任务卡片ID:" + JSON.toJSONString(param));
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            JSONObject jsonObj = new JSONObject(param);
            String dataId = StrKit.str(jsonObj.get("id"));
            FormBean formBean = cap4FormManager.getFormByFormCode(templateCode);
            String projectCode = StrKit.str(formBean.getFieldBeanByDisplay("项目编码").getName());
            String projectName = StrKit.str(formBean.getFieldBeanByDisplay("项目名称").getName());
            String taskCode = StrKit.str(formBean.getFieldBeanByDisplay("任务编号").getName());
            String templateCode = StrKit.str(formBean.getFieldBeanByDisplay("流程模板编号").getName());

            FormDataMasterBean formDataMasterBean = cap4FormManager.getDataMasterBeanById(Long.parseLong(dataId), formBean, null);
            String projectCodeValue = StrKit.str(formDataMasterBean.getFieldValue(projectCode));
            String projectNameValue = StrKit.str(formDataMasterBean.getFieldValue(projectName));
            String taskCodeValue = StrKit.str(formDataMasterBean.getFieldValue(taskCode));
            String templateCodeValue = StrKit.str(formDataMasterBean.getFieldValue(templateCode)).trim();
            if("".equals(templateCodeValue)){
                resultMap.put("code", 500);
                resultMap.put("data", "");
                resultMap.put("msg", "【流程模板编号】为空值,请管理员维护流程模版编号!");
                return ok(JSON.toJSONString(resultMap));
            }

            User user = AppContext.getCurrentUser();
            String loginName = user.getLoginName();
            Map<String, Object> tokenMap = new HashMap<String, Object>();
            tokenMap.put("userName", userName);
            tokenMap.put("loginName", loginName);
            tokenMap.put("password", password);
//          tokenMap.put("password", "a5a420f5-7811-4aba-8294-2478c7a7faff");
            String tokenJson = JSON.toJSONString(tokenMap);
            String token_result = HttpKit.post(tokenUrl, new HashMap<String, Object>(), tokenJson);
            String tokenId = "";
            try {
                JSONObject token_obj = JSONObject.parseObject(token_result);
                tokenId = StrKit.str(token_obj.get("id"));
            } catch (JSONException e) {
            }

            FormBean taskFormBean = cap4FormManager.getFormByFormCode(templateCodeValue);
            if(taskFormBean == null){
                resultMap.put("code", 500);
                resultMap.put("data", "");
                resultMap.put("msg", "流程模板编号【"+templateCodeValue+"】有误,请联系管理员维护!");
                return ok(JSON.toJSONString(resultMap));
            }

            String tableName = taskFormBean.getMasterTableBean().getTableName();
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("appName", "collaboration");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("templateCode", templateCodeValue);
            dataMap.put("draft", "1");

            Map<String, Object> mainMap = new HashMap<String, Object>();
            mainMap.put("项目编码", projectCodeValue);
            mainMap.put("项目名称", projectNameValue);
            mainMap.put("任务编码", taskCodeValue);
            Map<String, Object> data1Map = new HashMap<String, Object>();
            data1Map.put(tableName, mainMap);
            dataMap.put("data", data1Map);
            paramMap.put("data", dataMap);

            String dataJson = JSON.toJSONString(paramMap);
            log.info("发送协同流程json:"+dataJson);

            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("token", tokenId);
            String result = HttpKit.post(bpmUrl, headers, dataJson);
            log.info("发送协同流程接口返回信息:"+result);
            JSONObject resultObj = JSONObject.parseObject(result);
            String code = StrKit.str(resultObj.get("code"));
            String msg = StrKit.str(resultObj.get("message"));

            if ("0".equals(code)) {
                String affairId = StrKit.str(resultObj.getJSONObject("data").getJSONObject("app_bussiness_data").get("affairId"));
                String summaryId = StrKit.str(resultObj.getJSONObject("data").getJSONObject("app_bussiness_data").get("summaryId"));
                StringBuilder stb = new StringBuilder();
                stb.append(accessAddress).append("/seeyon/collaboration/collaboration.do?method=newColl&summaryId=");
                stb.append(summaryId).append("&affairId=").append(affairId).append("&from=waitSend&subState=1&showTab=true");
                stb.append("&recommendMenuId=").append(affairId).append("&menuSummary=add&portalId=1");
                String waitUrl = stb.toString();
                resultMap.put("code", 200);
                resultMap.put("data", waitUrl);
                resultMap.put("msg", "");
            } else {
                resultMap.put("code", 500);
                resultMap.put("data", "");
                resultMap.put("msg", msg);
            }
            return ok(JSON.toJSONString(resultMap));
        } catch (Exception e) {
            log.error("新建任务失败：", e);
            resultMap.put("code", 500);
            resultMap.put("data", "");
            resultMap.put("msg", e.getMessage());
            return ok(JSON.toJSONString(resultMap));
        }
    }
}
